using System;
using System.Collections.Generic;
using System.Text;
using MCromwell.StaffIntranet.Task.Tasks;
using MCromwell.StaffIntranet.DTO;
using MCromwell.StaffIntranet.DependencyInjection;

namespace MCromwell.StaffIntranet.Presenters
{
    public class StaffSearchingPresenter
    {
        private IStaffViewingTask viewingTask;
        private IAuthenticationTask authenticationTask;
        private IStaffSearchingView view;

        public StaffSearchingPresenter(IStaffSearchingView view)
            : this(IoC.Resolve<IStaffViewingTask>(), IoC.Resolve<IAuthenticationTask>(), view)
        {
        }

        public StaffSearchingPresenter(IStaffViewingTask viewingTask, IAuthenticationTask authenticationTask, IStaffSearchingView view)
        {
            if (viewingTask == null)
                throw new ArgumentNullException("viewingTask", "viewing task cannot be null");

            if (authenticationTask == null)
                throw new ArgumentNullException("authenticationTask", "authentication task cannot be null");

            if (view == null)
                throw new ArgumentNullException("view", "view cannot be null");

            this.viewingTask = viewingTask;
            this.authenticationTask = authenticationTask;
            this.view = view;

            BindToViewEvents();
        }

        private void BindToViewEvents()
        {
            view.Initialize += new EventHandler<StaffSearchingInitializeEventArgs>(HandleViewInitialization);
        }

        void HandleViewInitialization(object sender, StaffSearchingInitializeEventArgs e)
        {
            CheckIfStaffCanBeEdited(e);
            SendLocationsToView();
        }

        private void SendLocationsToView()
        {
            IList<LocationDTO> locations = viewingTask.RetrieveAvailableLocations();
            view.DisplayAvailable(locations);
        }

        private void CheckIfStaffCanBeEdited(StaffSearchingInitializeEventArgs e)
        {
            bool validSession = authenticationTask.CheckSessionAgainst(e.SessionId);
            view.CanEditStaff = validSession;
        }
                        
        public IList<StaffDTO> SearchForStaffUsing(string LastName, string FirstName, int LocationId, int StartRowIndex, int MaximumRowSize, out int Total)
        {
            return viewingTask.SearchStaffUsing(LastName, FirstName, LocationId, StartRowIndex, MaximumRowSize, out Total);
        }
    }
}
